<template>
  <div id="box">
<!--    <button @click="pdfClick" style="">-->
<!--      pdf-->

<!--    </button>-->

    <!-- 图表展示位置 -->
    <basic-card class="card1">
      <!-- 日期选择 -->
      <!-- <van-cell is-link @click="showPopup">展示弹出层</van-cell> -->
      <div style="font-size: 15px; margin-top: 10px; color: black;padding-left:10px;padding-right: 20px ;display: flex;
  justify-content: space-between;">
        <span style="font-size: 15px; "> 收入对比</span>
        <span
            @click="showPopup"
        >
          <!-- {{currentDate.getFullYear()}}年{{currentDate.getMonth()+1}}月 -->
          {{ selectYear }}年{{ selectMonth }}月
          <van-icon name="arrow-down"/>
        </span>
      </div>
      <van-popup v-model="show" position="top"
      >
        <div>
          <van-datetime-picker
              v-model="currentDate"
              type="year-month"
              title="选择年月"
              :min-date="minDate"
              :max-date="maxDate"
              :formatter="formatter"
              @confirm="confirmClick"
              @cancel="cancelClick"
          />
        </div
        >
      </van-popup>

      <!--&lt;!&ndash;        某月的总金额展示&ndash;&gt;-->
      <!--      <div style="font-size: 24px; margin-top: 10px">-->

      <!--        {{-->
      <!--          (chartData.length == 0)-->
      <!--            ? "0.00"-->
      <!--            : formatMoneyWithCommas(chartData[clickIndex].value)-->
      <!--        }}-->
      <!--        <span class="fontColor" style="font-size: 10px">元</span>-->
      <!--        &lt;!&ndash; {{ chartData[clickIndex].value }} &ndash;&gt;-->
      <!--      </div>-->
      <!-- 图表展示 -->
      <div
          id="myChart"
          style="width: 340px; height: 270px"
          ref="my_chart"
      ></div>
    </basic-card>

    <!-- 下面的数据 -->
    <basic-card class="card2">
      <van-list
          v-model="loading"
          :finished="finished"
          finished-text=""
          @load="onLoad"
          class="myList"
          @list-text-line-height="100"
      >
        <van-cell
            class="myListItem"
            style="padding-top: 5px; padding-bottom: 1px"
        >
          <div>
            <span class="fontColor" style="font-size: 10px">月份</span>
            <span class="fontColor" style="font-size: 10px; float: right"
            >金额</span
            >
          </div>
        </van-cell>
        <van-cell
            class="myListItem"
            v-for="(item, index) in chartData"
            :key="index"
        >
          <div style="padding: 4px 0px">
<!--            <van-icon :color="color[index]" name="play"/>-->
            <span
            >{{ item.date.split(".")[0] }}年{{ item.date.split(".")[1] }}月
            </span>

            <span style="float: right">¥{{ item.value.toFixed(2)| formatfilter  }}</span>
          </div>
        </van-cell>
      </van-list>
    </basic-card>
  </div>
</template>

<script>
import BasicCard from "../BasicCard.vue";

export default {
  components: {BasicCard},
  name: "LineChart",
  data() {
    return {
      // 日期选择相关
      minDate: new Date(2018, 0, 1),
      maxDate: new Date(),
      currentDate: new Date(),
      show: false,
      selectYear: 2023,
      selectMonth: 7,
      // 图表相关
      chartInstance: null,
      chartData: [],
      x_data: null,
      y_data: null,
      clickIndex: 6,
      // color: [
      //   "rgb(105,219,219)",
      //   "rgb(162,230,148)",
      //   "rgb(110,220,174)",
      //   "rgb(255,137,138)",
      //   "rgb(255,217,123)",
      //   "rgb(245,167,190)",
      //   "#B1B2FF",
      //   "#fed9b7",
      //   "#e4c1f9",
      //   "#f7a072",
      //   "#b8e0d2",
      //   "#ff5d8f",
      //   "#49b6ff",
      //   "#ffc8dd",
      // ],
      color1: "rgb(80, 135, 236)",
      color2: "#b2b2b2",

      // 列表相关
      list: [],
      loading: false,
      finished: false,
    };
  },
  methods: {
    // pdfClick() {
    //
    //   window.open('http://113.106.111.75:81/a.pdf',"_blank")
    // },
    // 获取x个月前的日期
    getXMonthsAgoDate(year, month, x) {
      // 将月份转换为0-11的索引
      month -= 1;

      // 计算总的月份差
      const totalMonths = year * 12 + month - x;

      // 计算新的年份和月份
      const newYear = Math.floor(totalMonths / 12);
      const newMonth = (totalMonths % 12) + 1;

      // 如果新的月份为0，说明要借位，年份减1，月份设为12月
      if (newMonth === 0) {
        return {
          year: newYear - 1,
          month: 12,
        };
      } else {
        return {
          year: newYear,
          month: newMonth,
        };
      }
    },
    showPopup() {
      this.show = true;
    },
    confirmClick(value) {

      this.selectYear = value.getFullYear();
      this.selectMonth = value.getMonth() + 1;
      // console.log(value.getFullYear());
      // console.log(value.getMonth() + 1);
      this.show = false;
      this.getData();
    },
    cancelClick() {
      this.show = false;
    },
    formatter(type, val) {
      if (type === "year") {
        return `${val}年`;
      } else if (type === "month") {
        return `${val}月`;
      }
      return val;
    },
    onLoad() {
      this.loading = false;
    },

    decimalToPercentage(decimal) {
      // 将小数转换为百分数并保留两位小数
      const percentage = (decimal * 100).toFixed(2);

      // 添加百分号
      return percentage + "%";
    },
    // 给金钱加逗号
    formatMoneyWithCommas(number) {
      if (number === undefined) {
        return "";
      }
      number = number.toFixed(2)
      // 将数字转换为字符串，并处理负数情况
      const strNumber = number.toString().replace(/^-/, "");

      // 分割整数和小数部分
      const [integerPart, decimalPart] = strNumber.split(".");

      // 处理整数部分，从右向左每隔三位插入逗号
      const formattedInteger = integerPart.replace(
          /\B(?=(\d{3})+(?!\d))/g,
          ","
      );

      // 如果有小数部分，拼接整数和小数部分，并返回结果
      if (decimalPart !== undefined) {
        return `${number < 0 ? "-" : ""}${formattedInteger}.${decimalPart}`;
      }

      // 如果没有小数部分，直接返回整数部分
      return `${number < 0 ? "-" : ""}${formattedInteger}`;
    },
    initChart() {
      this.chartInstance = this.$echarts.init(this.$refs.my_chart, null, {
        renderer: "svg",
      });
      //   this.chartInstance = this.$echarts.init(this.$refs.my_chart);
    },
    async getData() {
      var startMonth = (this.selectYear) + "-" + (this.selectMonth < 10 ? "0" + this.selectMonth : this.selectMonth);

      var {year, month} = this.getXMonthsAgoDate(
          this.selectYear,
          this.selectMonth,
          6
      );
      var endMonth = year + "-" + (month < 10 ? "0" + month : month);
      // const url = "http://localhost:8082/merchanthome/monthsum?id=1&startMonth=" + endMonth + "&endMonth=" + startMonth
      const url = "/merchanthome/monthsum?id=1&startMonth=" + endMonth + "&endMonth=" + startMonth

      console.log(url)
      const {code, data} = await this.$http.get(
          url
      );
      console.log(data);

      this.chartData = data.data.map((item) => {
        return {
          date: item.month.replace("-", "."),
          value: item.total_income_amount,
        };
      });


      // this.chartData =
      // [
      //   { date: "2023.1", value: 1232523.15 },
      //   { date: "2023.2", value: 2324515.24 },
      //   { date: "2023.3", value: 1553214.52 },
      //   { date: "2023.4", value: 812312.33 },
      //   { date: "2023.5", value: 715522.56 },
      //   { date: "2023.6", value: 1153422.65 },
      //   { date: "2023.7", value: 1252233.32 },
      // ];
      // 得到date的数据
      // this.x_data = this.chartData.map((item) => {
      //   return item.date;
      // });
      // TODO: x_date
      this.x_data = this.chartData.map((item) => {
        return parseInt(item.date.split('.')[1]) + '月';
      });
      // console.log(this.x_data);
      // 得到value的数据
      this.y_data = this.chartData.map((item) => {
        return item.value;
      });
      // 将chartData按照date倒排序
      this.chartData.sort((a, b) => {
        return Date.parse(b.date) - Date.parse(a.date);
      });
      this.clickIndex = this.chartData.length - 1;
    },
    updateChart() {
      // 样式化中间的文字
      // const
      this.chartInstance.setOption(this.option);
    },
    ininDate() {
      this.selectYear = this.currentDate.getFullYear();
      this.selectMonth = this.currentDate.getMonth() + 1;
    },
  },

  watch: {
    chartData() {
      this.updateChart();
    },
    color() {
      this.updateChart();
    },
  },
  computed: {
    color(){
      // return this.$store.state.checked ? this.color2 : this.color1
      return this.$store.state.monthBarColor[this.$store.state.styleNum]
    },
    option() {
      return {
        // grid: {
        //   x: 10,
        //   y: 10,
        //   x2: 10,
        //   y2: 30,
        // },
        // TODO: 表格位置
        grid: {
          x: 80,
          y: 40,
          x2: 20,
          y2: 30,
        },
        // label : {show: true},   //顶部显示数值
        xAxis: {
          type: "category",
          data: this.x_data,

          // data: [
          //   "2019.1",
          //   "2019.2",
          //   "2019.3",
          //   "2019.4",
          //   "2019.5",
          //   "2019.6",
          //   "2019.7",
          // ],
          // axisLabel: { show: false },
          axisLine: {show: false},
          splitLine: {show: false},
          axisTick: {show: true},
        },
        // TODO：y轴的数据展示设置
        yAxis: {
          "show": true,
          type: "value",
          axisLabel: {show: true},
          axisLine: {show: false},
          splitLine: {show: true},
          axisTick: {show: false},
        },
        series: [
          {
            // // 将饼状图的旋转动画持续时间设为2000ms（2秒）
            animationDuration: 700,
            animationDurationUpdate: 700,
            // 将饼状图的动画渐变设置为线性
            animationEasing: 'linear',
            // data: [120, 200, 150, 80, 70, 110, 120],
            data: this.y_data,
            type: "bar",
            // 阴影
            showBackground: false,
            backgroundStyle: {
              color: "rgba(180, 180, 180, 0.1)",
            },
            color: this.color,
            itemStyle: {
              // TODO:是否有圆角
              // barBorderRadius: 5,
              color: (params) => {
                // console.log(params)
                return this.color;
              },
            },
          },
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.7)",
          },
        },
      };
    },
  },

  mounted() {
    this.ininDate();
    this.initChart();
    this.getData();
    this.updateChart();
    // console.log(this.chartInstance.getModel().option.color);
    // this.color = this.chartInstance.getModel().option.color;
    this.chartInstance.on("click", (params) => {
      // console.log(params);
      this.clickIndex = params.dataIndex;
      // this.$router.push({ path: "/detail" });
    });
  },
};
</script>

<style scoped>

#box {
  background-color: rgb(247, 248, 250);
  padding-top: 10px;
  min-height: 667px;
//animation-name: animationbox;
//animation-duration: 0.75s;
}



/*
.card1 {
  width: 350px;
  margin: 5px auto;
  box-shadow: 2px 3px 4px rgba(0, 0, 0, 0.09);
  padding: 5px 0px;
  text-align: center;
}
 */

.card1 {
  width: 345rem;
  margin: 5rem auto;
  box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.15);
  padding: 5rem 0rem;
  text-align: center;
}

.card2 {
  width: 325rem;
  margin: 5rem auto;
  box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.15);;
  margin-top: 10rem;
  padding: 5rem 10rem;
  animation-name: animationCard2;
  animation-duration: 0.7s;
}


/*
.card2 {
  width: 330px;
  margin: 5px auto;
  box-shadow: 2px 3px 4px rgba(0, 0, 0, 0.09);
  margin-top: 10px;
  padding: 5px 10px;
  animation-name: animationCard2;
  animation-duration: 0.7s;
}
 */



@keyframes animationCard2 {
  0% {
    opacity: 0;
    transform: translateY(200px);
  }
  100% {
    opacity: 1;
    transform: translateY(0px);
  }
}

.myList {
  text-align: left;
  /* padding: 5px; */
}

.myListItem {
  /* border-bottom: 1px solid #ebedf0; */
  /* height: 60px; */
  /* margin: auto,0; */
}

.fontColor {
  color: rgb(197, 198, 199);
}
</style>